<template>
  <div class="organizer-info">
    <div class="info-container" v-if="organizerInfo">
      <!-- 主办方ID在非编辑模式下显示 -->
      <div class="info-item" v-if="!isEditing">
        <label>主办方ID:</label>
        <span>{{ organizerInfo.orId }}</span>
      </div>
      
      <div class="info-item">
        <label>账号:</label>
        <span v-if="!isEditing">{{ organizerInfo.orAccount }}</span>
        <input v-else v-model="editForm.orAccount" class="edit-input" />
      </div>
      
      <div class="info-item">
        <label>主办方名称:</label>
        <span v-if="!isEditing">{{ organizerInfo.orName }}</span>
        <input v-else v-model="editForm.orName" class="edit-input" />
      </div>
      
      <div class="info-item">
        <label>负责人:</label>
        <span v-if="!isEditing">{{ organizerInfo.orPeopleName }}</span>
        <input v-else v-model="editForm.orPeopleName" class="edit-input" />
      </div>
      
      <div class="info-item">
        <label>联系方式:</label>
        <span v-if="!isEditing">{{ organizerInfo.orContact }}</span>
        <input v-else v-model="editForm.orContact" class="edit-input" />
      </div>
      
      <!-- 编辑模式下显示旧密码和新密码输入框 -->
      <div class="info-item" v-if="isEditing">
        <label>旧密码:</label>
        <input v-model="oldPassword" type="password" placeholder="请输入旧密码" class="edit-input" />
      </div>
      
      <div class="info-item" v-if="isEditing">
        <label>新密码:</label>
        <input v-model="editForm.orPassword" type="password" placeholder="请输入新密码（不修改请留空）" class="edit-input" />
      </div>
      
      <!-- 注册时间在非编辑模式下显示 -->
      <div class="info-item" v-if="!isEditing">
        <label>注册时间:</label>
        <span>{{ formatDate(organizerInfo.orTime) }}</span>
      </div>
      
      <!-- 状态在非编辑模式下显示 -->
      <div class="info-item" v-if="!isEditing">
        <label>状态:</label>
        <span>{{ organizerInfo.orIsUsing === 1 ? '启用' : '禁用' }}</span>
      </div>
      
      <!-- 按钮区域 -->
      <div class="button-group">
        <button v-if="!isEditing" @click="startEdit" class="edit-btn">修改账号信息</button>
        <button v-if="!isEditing" @click="logout" class="logout-btn">退出登录</button>
        
        <button v-if="isEditing" @click="cancelEdit" class="cancel-btn">取消修改</button>
        <button v-if="isEditing" @click="saveChanges" class="save-btn">保存新信息</button>
      </div>
    </div>
    <div v-else class="loading" v-loading="loading">
      {{ loading ? '加载中...' : '暂无数据' }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

// 定义主办方信息接口
interface OrganizerInfo {
  orId: number
  orAccount: string
  orPassword: string
  orName: string
  orPeopleName: string
  orContact: string
  orTime: string
  orIsUsing: number
}

// 定义编辑表单接口
interface EditForm {
  orAccount: string
  orName: string
  orPeopleName: string
  orContact: string
  orPassword: string
}

// 响应式数据
const organizerInfo = ref<OrganizerInfo | null>(null)
const loading = ref<boolean>(false)
const isEditing = ref<boolean>(false)
const oldPassword = ref<string>('')
const router = useRouter()

// 编辑表单数据
const editForm = ref<EditForm>({
  orAccount: '',
  orName: '',
  orPeopleName: '',
  orContact: '',
  orPassword: ''
})

// 格式化日期显示
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取主办方信息
const fetchOrganizerInfo = async () => {
  loading.value = true
  try {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    console.log('发送请求时的token:', token)
    // 发送请求获取主办方信息
    const response = await axios.get('http://localhost:8080/organizer/getCurrent', {
      headers: {
        // 'Authorization': `Bearer ${token}`
        'token': token // 直接传 token，字段名改为「token」，不带 Bearer
      }
    })
    
    // 检查响应是否成功
    if (response.data.success) {
      organizerInfo.value = response.data.data
    } else {
      console.error('获取主办方信息失败:', response.data)
    }
  } catch (error) {
    console.error('请求出错:', error)
  } finally {
    loading.value = false
  }
}

// 开始编辑
const startEdit = () => {
  if (organizerInfo.value) {
    // 初始化编辑表单数据
    editForm.value = {
      orAccount: organizerInfo.value.orAccount,
      orName: organizerInfo.value.orName,
      orPeopleName: organizerInfo.value.orPeopleName,
      orContact: organizerInfo.value.orContact,
      orPassword: ''
    }
    isEditing.value = true
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  oldPassword.value = ''
}

// 保存更改
const saveChanges = async () => {
  if (!organizerInfo.value) return
  
  // 检查旧密码是否输入
  if (!oldPassword.value) {
    alert('请输入旧密码')
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    
    // 构造要发送的数据
    const data = {
      orId: organizerInfo.value.orId,
      orAccount: editForm.value.orAccount,
      orName: editForm.value.orName,
      orPeopleName: editForm.value.orPeopleName,
      orContact: editForm.value.orContact,
      oldPassword: oldPassword.value,
      orPassword: editForm.value.orPassword || undefined // 只有当新密码不为空时才添加新密码
    }
    
    const response = await axios.post('http://localhost:8080/organizer/updateInfo', data, {
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.success) {
      alert('信息更新成功，请重新登录')
      // 退出登录并跳转到登录页
      localStorage.removeItem('token')
      router.push('/login')
    } else {
      alert('更新失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('更新信息出错:', error)
    alert('更新信息时发生错误')
  }
}

// 退出登录
const logout = async () => {
  try {
    const token = localStorage.getItem('token')
    // 调用后端退出登录接口
    await axios.post('http://localhost:8080/organizer/logout', {}, {
      headers: {
        'token': token
      }
    })
  } catch (error) {
    console.error('退出登录时出错:', error)
  } finally {
    // 清空token并跳转到登录页
    localStorage.removeItem('token')
    router.push('/login')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrganizerInfo()
})
</script>

<style scoped>
.organizer-info {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.organizer-info h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.info-container {
  max-width: 600px;
  margin: 0 auto;
  background: #f9f9f9;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: bold;
  width: 100px;
  color: #666;
}

.info-item span {
  flex: 1;
  color: #333;
}

.info-item input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 3px;
}

.edit-input {
  flex: 2 !important;
}

.button-group {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.button-group button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.edit-btn, .save-btn {
  background-color: #409eff;
  color: white;
}

.logout-btn, .cancel-btn {
  background-color: #f4f4f5;
  color: #606266;
}

.button-group button:hover {
  opacity: 0.8;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}
</style>